package com.example.aslongastoday.ui.mine;

import static android.content.Context.MODE_PRIVATE;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.aslongastoday.util.CloudUtil;
import com.example.aslongastoday.util.MD5Utils;
import com.example.aslongastoday.R;

public class RegisterFragment extends Fragment implements View.OnTouchListener{

    private View view;

    private ImageView iv_back;

    private EditText et_user_name,et_psw,et_psw_again;
    private String userName,psw,pswAgain;
    private Button btn_register;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_register, container, false);
        view.setOnTouchListener(this);

        iv_back = view.findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            private FragmentManager fragmentManager;
            @Override
            public void onClick(View v) {
                //退出fragment
                fragmentManager = getActivity().getSupportFragmentManager();
                fragmentManager.popBackStack();
            }
        });

        btn_register=view.findViewById(R.id.btn_register);
        et_user_name=view.findViewById(R.id.et_user_name);
        et_psw=view.findViewById(R.id.et_psw);
        et_psw_again=view.findViewById(R.id.et_psw_again);
        btn_register.setOnClickListener(new View.OnClickListener() {
            private FragmentManager fragmentManager;
            @Override
            public void onClick(View v) {
                //获取输入在相应控件中的字符串
                getEditString();
                //判断输入框内容
                if(TextUtils.isEmpty(userName)){
                    Toast.makeText(getContext(), "请输入用户名", Toast.LENGTH_SHORT).show();
                    return;
                }else if(TextUtils.isEmpty(psw)){
                    Toast.makeText(getContext(), "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }else if(TextUtils.isEmpty(pswAgain)){
                    Toast.makeText(getContext(),  "请再次输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }else if(!psw.equals(pswAgain)){
                    Toast.makeText(getContext(),  "输入两次的密码不一样", Toast.LENGTH_SHORT).show();
                    return;
                    /**
                     *从SharedPreferences中读取输入的用户名，判断SharedPreferences中是否有此用户名
                     */
                }else if(isExistUserName(userName)){
                    Toast.makeText(getContext(), "此账户名已经存在", Toast.LENGTH_SHORT).show();
                    return;
                }else{
                    //把账号、密码和账号标识保存到sp里面
                    /**
                     * 远程接口，进行注册，保存账号和密码到SharedPreferences中
                     */
                    saveRegisterInfo(userName, psw);
                    Toast.makeText(getContext(), "注册成功", Toast.LENGTH_SHORT).show();
                    fragmentManager = getActivity().getSupportFragmentManager();
                    fragmentManager.popBackStack();
                }
            }
        });

        return view;
    }

    private boolean isExistUserName(String userName){
        boolean has_userName=false;
        //mode_private SharedPreferences sp = getSharedPreferences( );
        // "loginInfo", MODE_PRIVATE
        SharedPreferences sp=getContext().getSharedPreferences("loginInfo", MODE_PRIVATE);
        //获取密码
        String spPsw=sp.getString(userName, "");//传入用户名获取密码
        //如果密码不为空则确实保存过这个用户名
        if(!TextUtils.isEmpty(spPsw)) {
            has_userName=true;
        }
        return has_userName;
    }

    private void getEditString(){
        userName=et_user_name.getText().toString().trim();
        psw=et_psw.getText().toString().trim();
        pswAgain=et_psw_again.getText().toString().trim();
    }

    @SuppressLint("LongLogTag")
    private void saveRegisterInfo(final String userName, final String psw){
        String md5Psw = MD5Utils.md5(psw);//把密码用MD5加密
        //loginInfo表示文件名, mode_private SharedPreferences sp = getSharedPreferences( );
        SharedPreferences sp=getContext().getSharedPreferences("loginInfo", MODE_PRIVATE);
        //获取编辑器， SharedPreferences.Editor  editor -> sp.edit();
        SharedPreferences.Editor editor=sp.edit();
        //以用户名为key，密码为value保存在SharedPreferences中
        //key,value,如键值对，editor.putString(用户名，密码）;
        editor.putString(userName, md5Psw);
        //提交修改 editor.commit();
        editor.commit();
        try {
            CloudUtil.Register(userName,md5Psw);
        } catch (Exception e) {
            Log.e("RegisterFragment:saveRegisterInfo","调用远端接口注册失败");
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return true;
    }
}